import React from "react";
import {connect} from "react-redux";
import menuRoute from "routes/menuRoute";
import constants from "share/constants";
import configureStore from "stores";
import {setRequest, setMyAvailReqForms} from "actions/cache";
import {
  messages,
  dealCache,
  queryCurrencyPrecision,
  deepFullCopy,
} from "share/common";
import {
  Form,
  Table,
  Button,
  Tag,
  Input,
  Popover,
  Dropdown,
  Icon,
  Menu,
  message,
  Modal,
  Select,
} from "antd";
import SearchArea from "components/search-area";

const Search = Input.Search;
const FormItem = Form.Item;
const Option = Select.Option;
import requestService from "containers/request/request.service";
import debounce from "lodash.debounce";
import moment from "moment";
import Stations from "components/template/proxies/stations";
import Proxies from "components/template/proxies/proxies";
import "styles/request/request.scss";
import ResizeTable from "components/resize-table";

class ApplicationList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hideSearchForm: true, //task#43212：申请单列表页UI改造-隐藏搜索条件
      loading: false,
      type: this.getType().type, // 二期申请单类型
      requestTypes: [], //申请单类型
      checkboxListForm: [
        {
          id: "status",
          single: true,
          items: [
            {
              label: messages("request.key277" /*状态*/),
              key: "statusWithReject",
              checked: ["1001100210031004100510061007100810121013100910141016101710181019"],
              options: [
                {
                  label: messages("request.key278" /*全部*/),
                  value: "1001100210031004100510061007100810121013100910141016101710181019",
                },
                {
                  label: messages("request.key279" /*编辑中*/),
                  value: "10011000",
                  state: "processing",
                },
                {
                  label: messages("request.key280" /*已撤回*/),
                  value: "10011001",
                  state: "warning",
                },
                {
                  label: messages("request.key281" /*已驳回*/),
                  value: "10011002",
                  state: "error",
                },
                {
                  label: messages("request.key283" /*审批中*/),
                  value: "10021000",
                  state: "processing",
                },
                {
                  label: messages("request.key284" /*已通过*/),
                  value: "10031000",
                  state: "success",
                },
                {
                  label: messages("request.key7" /*已关闭*/),
                  value: "1009",
                  state: "default",
                },
                {
                  label: messages("components.keyS01" /*已出库*/),
                  value: "1012",
                  state: "error",
                },
                {
                  label: messages("components.keyS02" /*已签收*/),
                  value: "1013",
                  state: "success",
                },
                {
                  label: messages("components.keyS03" /*待发货*/),
                  value: "1014",
                  state: "success",
                },
                {
                  label: messages("components.keyS04" /*已发货*/),
                  value: "1016",
                  state: "success",
                },
                {
                  label: messages("components.keyS05" /*已确认*/),
                  value: "1017",
                  state: "success",
                },
                {
                  label: messages("components.keyS06" /*发货中*/),
                  value: "1018",
                  state: "success",
                },
                {
                  label: messages("components.keyS07" /*待发放*/),
                  value: "1019",
                  state: "success",
                },
              ],
            },
          ],
        },
        {
          id: "formOID",
          single: true,
          items: [
            {
              label: messages("request.key290" /*单据名称*/),
              key: "formOID",
              options: [
                {label: messages("request.key278" /*全部*/), value: "all"},
              ],
              checked: ["all"],
            },
          ],
        },
      ],
      searchForm: [
        /*{type: 'items', id: 'dateRange', items: [
          {type: 'date', id: 'startDate', label: messages('request.key291'/!*起始日期*!/)},
          {type: 'date', id: 'endDate', label: messages('request.key292'/!*结束日期*!/)}
        ]},
        {
          type: 'list',
          id: 'applicantOIDs',
          label: messages('approve.key64'/!*申请人*!/),
          listType: 'user_condition',
          labelKey: 'fullName',
          valueKey: 'userOID',
          listExtraParams:{roleType: 'TENANT'}
        }*/
      ],
      searchParams: {status: "1001100210031004100510061007100810121013100910141016101710181019"},
      columns: [
          {
            title: messages("common.sequence"),
            dataIndex: "index",
            render: (value, record, index) =>
              index + 1 + this.state.pageSize * this.state.page,
            width: 48,
          },
          {
            title: messages("request.key294" /*创建日期*/),
            dataIndex: "createdDate",
            width: 100,
            render: (value, record) => moment(value).format("YYYY-MM-DD"),
          },
          {
            title: messages("request.key293" /*申请人*/),
            dataIndex: "applicantName",
            width: 100,
          },
          {
            title: messages("request.key290" /*单据名称*/),
            dataIndex: "formName",
            // width: 130,
            render: (value) =>
              value ? (
                <Popover placement="topLeft" content={value}>
                  {value}
                </Popover>
              ) : (
                "-"
              ),
          },
          {
            title: messages("request.key295" /*事由*/),
            dataIndex: "title",
            // width: 100,
            render: (value) =>
              value ? (
                <Popover placement="topLeft" content={value}>
                  {value}
                </Popover>
              ) : (
                "-"
              ),
          },
          {
            title: messages("request.key296" /*单号*/),
            dataIndex: "businessCode",
            sorter: true,
            width: 200,
            render: (value, record) =>
              value ? (
                record.formCode === "OFFLINE_FLIGHT_CONFIRMATION_FORM" ||
                record.formCode === "OFFLINE_HOTEL_CONFIRMATION_FORM" ? (
                  <Popover
                    placement="topLeft"
                    content={record.travelNo + "-" + value}
                  >
                    {record.travelNo + "-" + value}
                  </Popover>
                ) : (
                  <Popover placement="topLeft" content={value}>
                    {value}
                  </Popover>
                )
              ) : (
                "-"
              ),
          },
          {
            title: messages("request.key225" /*币种*/),
            dataIndex: "originCurrencyCode",
            width: 50,
          },
          {
            title: messages("request.key226" /*金额*/),
            dataIndex: "originCurrencyTotalAmount",
            align: "right",
            width: "7%",
            render: (value, record) =>
              !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008'].includes(record.formCode)
                ? this.filterMoney(
                  value,
                  queryCurrencyPrecision(record.originCurrencyCode)
                )
                : value
                  ? value
                  : "-",
          },
          {
            title: messages("request.key230" /*本币金额*/),
            dataIndex: "totalAmount",
            align: "right",
            width: "8%",
            render: (value, record) => {
              //不考虑停用单据totalAmount为0的情况了，bug21199
              return !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008'].includes(record.formCode)
                ? this.filterMoney(
                  value || 0,
                  queryCurrencyPrecision(record.currencyCode)
                )
                : value
                  ? value
                  : "-";
            },
          },
          {
            title: messages("common.column.status") /** 状态 */,
            dataIndex: "status",
            width: props.language.code === "zh_cn" ? 100 : "13%",
            render: (value, record) => {
              let applicationType = 2005; //申请单
              let text;
              let color;
              if (
                record.closed ||
                record.participantClosed ||
                (record.applicationParticipant &&
                  record.applicationParticipant.closed === 1)
              ) {
                text = messages("request.key7" /*已关闭*/);
                color = "#d9d9d9";
              } else {
                text =
                  constants.getTextByValue(
                    String(value + "" + applicationType),
                    "documentStatus"
                  ) ||
                  constants.getTextByValue(
                    String(value + "" + record.rejectType),
                    "documentStatus"
                  ) ||
                  constants.getTextByValue(String(value), "documentStatus");
                color =
                  constants.getTextByValue(
                    String(value + "" + applicationType),
                    "documentStatus",
                    "color"
                  ) ||
                  constants.getTextByValue(
                    String(value + "" + record.rejectType),
                    "documentStatus",
                    "color"
                  ) ||
                  constants.getTextByValue(
                    String(value),
                    "documentStatus",
                    "color"
                  );
              }
              return <Tag color={color}>{text}</Tag>;
            },
          },
        ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100", "200"],
      },
      sort: "",
      cacheSearchData: {}, //缓存筛选的数据
      newRequest: menuRoute.getRouteItem(`new-${this.getType().key}`, "key"), //新建申请单
      jdRequestEdit: menuRoute.getRouteItem(
        `jd-${this.getType().key}-edit`,
        "key"
      ), //京东申请单编辑页
      requestEdit: menuRoute.getRouteItem(`${this.getType().key}-edit`, "key"), //申请单编辑页
      requestDetail: menuRoute.getRouteItem(
        `${this.getType().key}-detail`,
        "key"
      ), //商务及礼品申请单详情页
      requestEditDetail: menuRoute.getRouteItem(
        "business-and-gift-application-giftDetail",
        "key"
      ), // 礼品申请单详情页
      key: 1,
    };
    this.handleSearch = debounce(this.handleSearch, 250);
  }

  componentWillMount() {}

  // 二期申请单下的子菜单重新获取组件数据
  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps) == JSON.stringify(this.props)) {
      let json = this.getType();
      this.setState(
        {
          type: json.type,
          newRequest: menuRoute.getRouteItem(`new-${json.key}`, "key"), // 新建申请单
          jdRequestEdit: menuRoute.getRouteItem(`jd-${json.key}-edit`, "key"), //京东申请单编辑页
          requestEdit: menuRoute.getRouteItem(`${json.key}-edit`, "key"), //申请单编辑页
          requestDetail: menuRoute.getRouteItem(`${json.key}-detail`, "key"), //申请单详情页
          key: this.state.key + 1,
        },
        () => {
          this.clear();
          this.getForms();
        }
      );
      return false;
    } else {
      return true;
    }
  }

  componentDidMount() {
    this.getForms();
  }

  // 根据当前url判断当前是哪个申请单
  // type: 1(出行及预订) 2(商务应酬及礼品) 3(公务卡申请) 4(特殊事项申请) 5(代理申请) 6(工会申请单) 7(健康码申请)
  getType() {
    const path = this.props.route.path;
    return (
      [
        {type: 1, key: "travel-and-booking"},
        {type: 2, key: "business-and-gift-application"},
        {type: 3, key: "public-service-card-application"},
        {type: 4, key: "other-application"},
        {type: 5, key: "agency-application"},
        {type: 6, key: "union-request"},
        {type: 9, key: "green-code-request"},
      ].find((item) => {
        return path.indexOf(item.key) > -1;
      }) || {
        key: "request",
        type: undefined,
      }
    );
  }

  //存储筛选数据缓存
  setCache = (result) => {
    const {page, pageSize} = this.state;
    result.pageSize = pageSize;
    result.page = page;
    // this.setState({ cacheSearchData: result });
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.request;
    let {checkboxListForm} = this.state;
    if (result && JSON.stringify(result) !== "{}") {
      checkboxListForm.map((item, index) => {
        checkboxListForm[index].items[0].checked = [result[item.id]] || [];
      });
      this.setState({cacheSearchData: result, checkboxListForm}, () => {
        this.dealCache(result);
      });
    } else {
      this.getList();
    }
  };

  //处理筛选缓存数据
  dealCache = (result) => {
    const {searchForm, pagination} = this.state;
    if (result) {
      dealCache(searchForm, result);
      pagination.pageSize = result.pageSize ? result.pageSize : 10;
      this.setState(
        {
          pagination,
          pageSize: result.pageSize ? result.pageSize : 10,
          page: result.page,
        },
        () => {
          this.search(result);
          configureStore.store.dispatch(setRequest(null));
        }
      );
    }
  };

  //获取单据列表
  getForms = () => {
    let {type, checkboxListForm} = this.state;
    //formType：101（申请单）、102（报销单）、103（全部）
    requestService.getMyDocumentType(101, undefined, true, type).then((res) => {
      let options = [
        {label: messages("request.key278" /*全部*/), value: "all"},
      ];
      res.data.map((item) => {
        options.push({label: item.formName, value: item.formOID});
      });
      checkboxListForm.map((form) => {
        if (form.id === "formOID") {
          form.items.map((item) => {
            item.key === "formOID" && (item.options = options);
          });
        }
      });
      //保存表单信息，后面机酒确认单跳转原申请单时需要用对应的formOID
      configureStore.store.dispatch(setMyAvailReqForms(res.data));
      this.setState({checkboxListForm, requestTypes: res.data}, () => {
        this.getCache();
      });
    });
  };

  getList = () => {
    // https://pmo.mcd.com.cn/jira/browse/TES-837
    // 搜索优化，防止新搜索结果被旧搜索结果覆盖
    if (this.abortLatestGetList) this.abortLatestGetList();
    let aborted = false;
    this.abortLatestGetList = () => {
      aborted = true;
    };

    const {page, pageSize, searchParams, pagination, sort, type} = this.state;
    this.setState({loading: true});
    if (sort) {
      searchParams.sort = sort;
    }
    requestService
      .getRequestList(page, pageSize, type, searchParams)
      .then((res) => {
        if (aborted) {
          return;
        }
        pagination.total = Number(res.headers["x-total-count"]) || 0;
        pagination.current = page + 1;
        this.setState({
          loading: false,
          data: res.data,
          pagination,
        });
      })
      .catch(() => {
        this.setState({loading: false});
        message.error(messages("common.error1"));
      });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const {searchParams} = this.state;
    let page = pagination.current;
    let sort = "";
    if (sorter.order) {
      sort = `${sorter.columnKey},${
        sorter.order === "ascend" ? "ASC" : "DESC"
      }`;
    }
    this.setState(
      {
        page: page - 1,
        pageSize: pagination.pageSize,
        sort,
      },
      () => {
        this.setCache(searchParams);
        this.getList();
      }
    );
  };

  search = (values) => {
    let {pagination} = this.state;
    pagination.total = 0;
    this.setCache({...values});
    values.formOID === "all" && (values.formOID = "");
    values.startDate &&
    (values.startDate = moment(values.startDate).format(
      "YYYY-MM-DD+00:00:00"
    ));
    values.endDate &&
    (values.endDate = moment(values.endDate).format("YYYY-MM-DD+23:59:59"));
    this.setState(
      {
        searchParams: values,
        page: values.page ? values.page : 0,
        pagination,
      },
      () => {
        console.log("valuessssssssssss");
        this.getList();
      }
    );
  };

  clear = () => {
    let {pagination} = this.state;
    pagination.total = 0;
    this.setCache({});
    this.setState(
      {
        cacheSearchData: {},
        searchParams: {status: "1001100210031004100510061007100810121013100910141016101710181019"},
        page: 0,
        pagination,
      },
      () => {
        this.getList();
      }
    );
  };

  handleSearch = (value) => {
    let {pagination} = this.state;
    pagination.total = 0;
    let searchParams = this.state.searchParams;
    searchParams.businessCode = encodeURIComponent(value);
    this.setState(
      {
        searchParams,
        page: 0,
        pagination,
      },
      () => {
        this.getList();
      }
    );
  };

  expandedRowRender = (record) => {
    let expandedFlag = false;
    if (
      record.warning ||
      record.rejectType === 1002 ||
      record.rejectType === 1003 ||
      record.participantClosed ||
      record.closed ||
      (record.applicationParticipant && record.applicationParticipant.closed) ||
      (record.referenceExpenseReportsCode &&
        record.referenceExpenseReportsCode.length) ||
      (record.warningList && JSON.parse(record.warningList).length)
    ) {
      expandedFlag = true;
    }
    let warningList = record.warningList ? JSON.parse(record.warningList) : [];
    return expandedFlag ? (
      <div className="expanded-row">
        {!!record.warning && (
          <div>
            {messages("request.key297" /*超预算*/)}：
            {JSON.parse(record.warning).message}
          </div>
        )}
        {record.rejectType === 1002 && (
          <div>
            {messages("request.key298" /*审批驳回*/)}：{record.rejectReason}
          </div>
        )}
        {record.rejectType === 1003 && (
          <div>
            {messages("request.key299" /*审核驳回*/)}：{record.rejectReason}
          </div>
        )}
        {!!(
          record.participantClosed ||
          record.closed ||
          (record.applicationParticipant &&
            record.applicationParticipant.closed)
        ) && <div>{messages("request.key300" /*关闭：该单据已关闭*/)}</div>}
        {!!(
          record.referenceExpenseReportsCode &&
          record.referenceExpenseReportsCode.length
        ) && (
          <div style={{whiteSpace: "normal"}}>
            {messages("request.key301" /*已关联*/)}：
            {messages("request.key302" /*报销单*/)}&nbsp;
            {record.referenceExpenseReportsCode.join(", ")}
          </div>
        )}
        {warningList &&
          warningList.map((warningItem) => {
            return (
              <div
                key={warningItem.externalPropertyName}
                className={
                  warningItem.type
                    ? "default-color-inverse-font"
                    : "default-color-font"
                }
              >
                {
                  messages("request.key648", {
                    arg1: warningItem.title,
                  }) /*标签：{arg1}*/
                }
              </div>
            );
          })}
      </div>
    ) : null;
  };

  handleRowClick = (record) => {
    console.log("【DEBUG] click record", record);
    const backUrlKey = this.getType().key;
    configureStore.store.dispatch(setRequest(this.state.cacheSearchData));

    const isOfflineOrder =
      [
        "OFFLINE_FLIGHT_CONFIRMATION_FORM",
        "OFFLINE_HOTEL_CONFIRMATION_FORM",
      ].indexOf(record.formCode) > -1;

    let action = 'edit'

    if (record.status === 1001 && !isOfflineOrder) {
      action = 'edit'
    } else {
      action = 'detail'
    }

    menuRoute.goForm(this, record.formCode, {
      action,
      backUrlKey,
      params: {
        formOID: record.formOID,
        applicationOID: record.applicationOID,
        id: record.id,
      }
    })
  };

  //新建申请单 非代提
  handleNewRequest = (formOID, jobId) => {
    const backUrlKey = this.getType().key;
    const {newRequest} = this.state;
    let url = newRequest.url;
    url = url.replace(":formOID", formOID);
    url = url.replace(":jobId", jobId);
    url += `?backUrlKey=${backUrlKey}`;
    this.context.router.push(url);
  };

  //新建申请单 代提
  handleNewProxy = (formOID, jobId, userOID, ifProxy) => {
    const backUrlKey = this.getType().key;
    const {newRequest} = this.state;
    let url = newRequest.url;
    url = url.replace(":formOID", formOID);
    url = url.replace(":applicantOID", userOID);
    url = url.replace(":jobId", jobId);
    if (ifProxy) {
      url = url.replace(":ifProxy", 1);
    }
    url += `?backUrlKey=${backUrlKey}`;
    this.context.router.push(url);
  };

  render() {
    const {
      loading,
      requestTypes,
      checkboxListForm,
      searchForm,
      columns,
      data,
      pagination,
      hideSearchForm,
      type,
    } = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 10, offset: 1},
    };
    let newColumns = deepFullCopy(columns);
    if (type === 1) {
      newColumns.splice(2, 0, {
        title: messages("mcd.request.travelStartDate" /*差旅出发日期*/),
        dataIndex: "travelStartDate",
        width: 100,
        render: (value, record) => moment(value).format("YYYY-MM-DD"),
      });
    }

    // 健康码
    if(type === 9){
      newColumns.splice(6,3)
      newColumns.splice(4,1)
      newColumns.splice(5, 0, {
        title: messages("request.key810",/*部门名称*/),
        dataIndex: "departmentName",
        // width: 130,
        render: (value) =>
          value ? (
            <Popover placement="topLeft" content={value}>
              {value}
            </Popover>
          ) : (
            "-"
          ),
      });
    }

    // 代理申请单不需要代理申请按钮
    let showProxy = true;
    if (this.props.route.path.indexOf("agency-application") > -1) {
      showProxy = false;
    }
    return (
      <div className="application-list">
        <SearchArea
          hideSearchForm={hideSearchForm}
          searchForm={searchForm}
          submitHandle={this.search}
          isReturnLabel
          clearHandle={this.clear}
          checkboxListForm={checkboxListForm}
          // key={Math.random()}
          key={this.state.key}
          wrappedComponentRef={(inst) => (this.formRef = inst)}
        />
        <div className="table-header">
          <div className="table-header-title">
            {
              messages("common.total", {
                total: pagination.total || 0,
              }) /*共搜索到 {total} 条数据*/
            }
          </div>
          <div className="table-header-buttons">
            <Stations
              formType={"101"}
              type={type}
              onOk={this.handleNewRequest}
            />
            {showProxy && (
              <Proxies
                formType={"101"}
                isAll={true}
                type={type}
                onOk={this.handleNewProxy}
              />
            )}
            <Search
              className="input-search"
              maxLength={100}
              placeholder={messages("request.key305" /*输入申请单号*/)}
              onChange={(e) => this.handleSearch(e.target.value)}
            />
          </div>
        </div>
        <ResizeTable
          rowKey="applicationOID"
          columns={newColumns}
          dataSource={data}
          pagination={pagination}
          expandedRowRender={(record) => this.expandedRowRender(record)}
          rowClassName={(record) =>
            record.warning ||
            (record.rejectType === 1002 &&
              record.rejectReason !== "CP:" &&
              record.rejectReason !== "CR:") ||
            record.rejectType === 1003 ||
            (record.referenceExpenseReportsCode &&
              record.referenceExpenseReportsCode.length) ||
            (record.warningList && JSON.parse(record.warningList).length) ||
            (record.applicationParticipant &&
              record.applicationParticipant.closed) ||
            record.participantClosed ||
            record.closed
              ? ""
              : "row-expand-display-none"
          }
          onRow={(record) => ({onClick: () => this.handleRowClick(record)})}
          onChange={this.handleTableChange}
          loading={loading}
          bordered
          size="middle"
        />
      </div>
    );
  }
}

ApplicationList.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    request: state.cache.request,
  };
}

const wrappedApplicationList = Form.create()(ApplicationList);

export default connect(mapStateToProps)(wrappedApplicationList);
